<template>
  <div class="login-container">
    <div class="login-card">
      <h2>彩票号码选择系统</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label>用户名</label>
          <input type="text" v-model="username" required placeholder="请输入用户名">
        </div>
        <div class="form-group">
          <label>密码</label>
          <input type="password" v-model="password" required placeholder="请输入密码">
        </div>
        <button type="submit" class="login-btn">登录</button>
        <p v-if="errorMsg" class="error-msg">{{ errorMsg }}</p>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { validateUser } from '../api/api'

const username = ref('')
const password = ref('')
const errorMsg = ref('')
const router = useRouter()

// 在handleLogin方法中修改存储方式
const handleLogin = async () => {
  if (!username.value || !password.value) {
    errorMsg.value = '请输入用户名和密码'
    return
  }

  const result = await validateUser(username.value, password.value)

  if (result && result.code === 20000) {
    // 存储完整的用户信息对象（包含token）
    localStorage.setItem('userInfo', JSON.stringify(result.data))
    router.push('/select')
  } else {
    errorMsg.value = result?.message || '登录失败，请检查用户名和密码'
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 350px;
  padding: 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 1.5rem;
  color: #333;
}

.form-group {
  margin-bottom: 1rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  color: #666;
}

input {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.login-btn {
  width: 100%;
  padding: 0.8rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-btn:hover {
  background-color: #359e75;
}

.error-msg {
  color: #ff4444;
  text-align: center;
  margin-top: 1rem;
}
</style>